package cn.iocoder.yudao.module.reading.controller.app.punch;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.reading.controller.app.punch.vo.PunchCalendarRespVO;
import cn.iocoder.yudao.module.reading.controller.app.punch.vo.PunchCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.punch.vo.PunchRecordRespVO;
import cn.iocoder.yudao.module.reading.controller.app.punch.vo.UserStatsRespVO;
import cn.iocoder.yudao.module.reading.controller.app.punch.vo.PunchUpdateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.punch.vo.PunchCalendarAllRespVO;
import cn.iocoder.yudao.module.reading.service.punch.PunchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户 APP - 学习打卡
 *
 * @author 李晨
 */
@Tag(name = "用户 APP - 学习打卡")
@RestController
@RequestMapping("/reading/punch")
@Validated
@Slf4j
public class PunchController {

    @Resource
    private PunchService punchService;

    @PostMapping("/create")
    @Operation(summary = "创建学习打卡")
    @PreAuthenticated
    public CommonResult<Long> createPunch(@Valid @RequestBody PunchCreateReqVO createReqVO) {
        Long userId = getLoginUserId();
        Long punchId = punchService.createPunch(userId, createReqVO);
        return success(punchId);
    }

    @GetMapping("/list")
    @Operation(summary = "获取打卡记录列表")
    @PreAuthenticated
    public CommonResult<List<PunchRecordRespVO>> getPunchRecords(
            @Parameter(description = "限制数量", example = "10") @RequestParam(value = "limit", required = false) Integer limit) {
        Long userId = getLoginUserId();
        List<PunchRecordRespVO> result = punchService.getPunchRecords(userId, limit);
        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "分页获取打卡记录列表")
    @PreAuthenticated
    public CommonResult<PageResult<PunchRecordRespVO>> getPunchRecordsPage(
            @Parameter(description = "页码", example = "1") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        Long userId = getLoginUserId();
        PageParam pageParam = new PageParam();
        pageParam.setPageNo(page);
        pageParam.setPageSize(limit);
        PageResult<PunchRecordRespVO> result = punchService.getPunchRecordsPage(userId, pageParam);
        return success(result);
    }

    @GetMapping("/calendar")
    @Operation(summary = "获取打卡日历")
    @PreAuthenticated
    public CommonResult<PunchCalendarRespVO> getPunchCalendar(
            @Parameter(description = "年月，格式：2024-01", example = "2024-01") @RequestParam(value = "yearMonth", required = false) String yearMonth) {
        Long userId = getLoginUserId();
        
        // 如果没有指定年月，使用当前年月
        if (yearMonth == null) {
            yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        }
        
        PunchCalendarRespVO result = punchService.getPunchCalendar(userId, yearMonth);
        return success(result);
    }

    @GetMapping("/can-punch-today")
    @Operation(summary = "检查今日是否可以打卡")
    @PreAuthenticated
    public CommonResult<Boolean> canPunchToday() {
        Long userId = getLoginUserId();
        boolean canPunch = punchService.canPunchToday(userId);
        return success(canPunch);
    }

    @GetMapping("/today")
    @Operation(summary = "获取今日打卡记录")
    @PreAuthenticated
    public CommonResult<PunchRecordRespVO> getTodayPunch() {
        Long userId = getLoginUserId();
        PunchRecordRespVO result = punchService.getTodayPunch(userId);
        return success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取打卡详情")
    @PreAuthenticated
    public CommonResult<PunchRecordRespVO> getPunchDetail(
            @Parameter(description = "打卡记录ID", required = true, example = "1") @PathVariable("id") Long id) {
        Long userId = getLoginUserId();
        PunchRecordRespVO result = punchService.getPunchDetail(userId, id);
        return success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除打卡记录")
    @PreAuthenticated
    public CommonResult<Boolean> deletePunch(
            @Parameter(description = "打卡记录ID", required = true, example = "1") @PathVariable("id") Long id) {
        Long userId = getLoginUserId();
        punchService.deletePunch(userId, id);
        return success(true);
    }

    @GetMapping("/user-stats")
    @Operation(summary = "获取用户阅读统计")
    @PreAuthenticated
    public CommonResult<UserStatsRespVO> getUserStats() {
        Long userId = getLoginUserId();
        log.info("获取用户阅读统计，用户ID: {}", userId);

        UserStatsRespVO result = punchService.getUserStats(userId);
        return success(result);
    }

    @GetMapping("/calendar/all")
    @Operation(summary = "获取完整打卡日历")
    @PreAuthenticated
    public CommonResult<PunchCalendarAllRespVO> getPunchCalendarAll() {
        Long userId = getLoginUserId();
        log.info("获取完整打卡日历，用户ID: {}", userId);

        PunchCalendarAllRespVO result = punchService.getPunchCalendarAll(userId);
        return success(result);
    }

    @PutMapping("/{punchId}")
    @Operation(summary = "更新打卡记录")
    @PreAuthenticated
    public CommonResult<Boolean> updatePunch(
            @Parameter(description = "打卡记录ID", required = true, example = "1") @PathVariable("punchId") Long punchId,
            @RequestBody @Valid PunchUpdateReqVO updateReqVO) {
        Long userId = getLoginUserId();
        log.info("更新打卡记录，用户ID: {}, 打卡记录ID: {}, 请求参数: {}", userId, punchId, updateReqVO);

        punchService.updatePunch(userId, punchId, updateReqVO);
        return success(true);
    }

    @GetMapping("/public/list")
    @Operation(summary = "获取公开打卡动态列表")
    @PreAuthenticated
    public CommonResult<List<PunchRecordRespVO>> getPublicPunchRecords(
            @Parameter(description = "限制数量", example = "20") @RequestParam(value = "limit", required = false) Integer limit) {
        Long currentUserId = getLoginUserId();
        List<PunchRecordRespVO> result = punchService.getPublicPunchRecords(currentUserId, limit);
        return success(result);
    }

    @GetMapping("/public/page")
    @Operation(summary = "分页获取公开打卡动态列表")
    @PreAuthenticated
    public CommonResult<PageResult<PunchRecordRespVO>> getPublicPunchRecordsPage(
            @Parameter(description = "页码", example = "1") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", example = "10") @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        Long currentUserId = getLoginUserId();
        PageParam pageParam = new PageParam();
        pageParam.setPageNo(page);
        pageParam.setPageSize(limit);
        PageResult<PunchRecordRespVO> result = punchService.getPublicPunchRecordsPage(currentUserId, pageParam);
        return success(result);
    }

}
